package com.inossem.warehousestorage_inossem.activity.in_storage.chuangyou;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.utils.log.LogUtils;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.change_storage.extra.ChangeStorageExtra;
import com.inossem.warehousestorage_inossem.activity.in_storage.extra.InStorageExtra;
import com.inossem.warehousestorage_inossem.activity.out_storage.extra.OutStorageExtra;
import com.inossem.warehousestorage_inossem.bean.inStorage.chuangyou.CYInStorageCheckSNCodeRequestBean;
import com.inossem.warehousestorage_inossem.bean.inStorage.chuangyou.CYInStorageProductionCheckSearchBean;
import com.inossem.warehousestorage_inossem.bean.inStorage.chuangyou.CYInStorageProductionOverviewBean;
import com.inossem.warehousestorage_inossem.bean.inStorage.chuangyou.CYInStorageStringBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.SNBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.SNItemInfo;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.inStorage.chuangyou.CYInStorageProductionCheckSearchRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.CYInStorageUtils;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author 王斯宇
 * @time on 2018/4/8 15:57
 * @email siyu.wang@inossem.com
 */
public class CYInStorageNoInStorageMaterielDetailActivity extends BaseActivity {
    public static final String PACKAGING_CODE = "1";

    public static final String SERIAL_NUMBER = "2";

    private TextView title , materialCode , materielDescription , location , productionNumber , packagingNumber ,assemblyLineNumber , productionNumberUnit , packagingCodeUnit;

    private ImageView search;

    private EditText editText;

    private CYInStorageProductionOverviewBean.OverViewBean.ItemListBean data;

    private List<SNBean.SNInfoBean> newList;//自定义，存放扫描的打包码和序列号

    private List<CYInStorageStringBean> packagingCodelist;//需要校验的打包码

    private List<SNBean.SNInfoBean.SnListBean> serialNumberlist;//需要校验的序列号

    private List<SNBean.SNInfoBean.SnListBean> newSNList;//扫描添加的序列号

    private PercentLinearLayout packagingCodeLayout, serialNumberLayout;

    private String mCondition , receiveMaterialCode , matId , mUnit , stock_input_id;

    private int i , j;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.cy_activity_in_storage_materiel_package_code_detail);
        initView(CYInStorageNoInStorageMaterielDetailActivity.this);
        initData(CYInStorageNoInStorageMaterielDetailActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        materialCode = (TextView) activity.findViewById(R.id.materielCode);
        materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        location = (TextView) activity.findViewById(R.id.location);
        productionNumber = (TextView) activity.findViewById(R.id.productionNumber);
        packagingNumber = (TextView) activity.findViewById(R.id.packagingNumber);
        assemblyLineNumber = (TextView) activity.findViewById(R.id.assemblyLineNumber);
        productionNumberUnit = (TextView) activity.findViewById(R.id.productionNumberUnit);
        packagingCodeUnit = (TextView) activity.findViewById(R.id.packagingCodeUnit);
        search = (ImageView) activity.findViewById(R.id.search);
        editText = (EditText) activity.findViewById(R.id.code);
        packagingCodeLayout = (PercentLinearLayout) activity.findViewById(R.id.packagingCodeLayout);
        serialNumberLayout = (PercentLinearLayout) activity.findViewById(R.id.serialNumberLayout);
    }
    private void initData(Activity activity) {
        title.setText(activity.getResources().getString(R.string.activity_receive_materiel_detail_title));
        ActivityUtils.initBackAndFunction(activity, getResources().getString(R.string.activity_receive_result_back), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                backAndUpdate();
//                finish();
            }
        });
        getExtra(activity);
        search.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (!TextUtils.isEmpty(editText.getText().toString())) {
                    ckeckSearch(activity , editText.getText().toString());
                }
            }
        });
        setmScanListener((String scanResult, int length) -> {
            switch (QRCodeUtils.getQRCodeType(scanResult)) {
                case QRCodeConstant.CY_TYPE_PACKAGE:
//                    mCondition = QRCodeUtils.DecryptQRCode(scanResult,QRCodeConstant.CY_PACKAGE_PARAMETER_PACKAGE);
                    ckeckSearch(activity , QRCodeUtils.DecryptQRCode(scanResult,QRCodeConstant.CY_PACKAGE_PARAMETER_PACKAGE));
                    break;
                case QRCodeConstant.CY_TYPE_SN:
                    ckeckSearch(activity , QRCodeUtils.DecryptQRCode(scanResult,QRCodeConstant.CY_SN_PARAMETER_SN));
//                    mCondition = QRCodeUtils.DecryptQRCode(scanResult,QRCodeConstant.CY_SN_PARAMETER_SN);
                    break;
                default:
                    Utils.middleToast(activity , "扫描码类型错误");
                    break;
            }
//            getData(activity, mCondition, mFactoryCode, mInventoryAddressCode, mBusinessType, mSpecialInventory);
        }, QRCodeConstant.CY_TYPE_PACKAGE , QRCodeConstant.CY_TYPE_SN);
        getData(activity);
    }
    private void getExtra(Activity activity) {
        matId = activity.getIntent().getStringExtra(InStorageExtra.MAT_ID);
        LogUtils.i("matID ======= " + matId);
    }
    private void getData (Context context) {
        data = CYInStorageUtils.getProductionMaterialDetail(context , matId);
        materialCode.setText(data.getMat_code());
        materielDescription.setText(data.getMat_name());
        assemblyLineNumber.setText(data.getProdction_line_name());
        location.setText(data.getLocation_code() + "-" + data.getLocation_name());
        mUnit = data.getName_zh();
        stock_input_id = data.getStock_input_id();
        productionNumberUnit.setText(mUnit);
        packagingCodeUnit.setText(mUnit);
        productionNumber.setText(data.getQty());
        packagingNumber.setText(data.getInStorageNumber() == null ? "0" : data.getInStorageNumber());

        if (data.getPackagingCodelist() == null ||data.getPackagingCodelist().size() == 0) {
            packagingCodelist = CYInStorageUtils.getPackagingCodelists(context , data.getStock_position_list() , matId);
        }else {
            packagingCodelist = data.getPackagingCodelist();
        }
        if (data.getSerialNumberlist() == null || data.getSerialNumberlist().size() == 0) {
            serialNumberlist = CYInStorageUtils.getSNCodelist(context , data.getStock_position_list() , matId);
        }else {
            serialNumberlist = data.getSerialNumberlist();
            LogUtils.i("serialNumberlistSize ===== " + serialNumberlist.size());
        }

        newList = data.getNew_stock_position_list() == null ? new ArrayList<>() : data.getNew_stock_position_list();
        newSNList = new ArrayList<>();
        i = 0;
//        j = 0;
        //初始化view
        for (int k = 0; k < newList.size(); k++) {
            if (TextUtils.isEmpty(newList.get(k).getPackage_code())) {
//                j = 1;
//                i = newList.size() - 1;
                for (int l = 0; l < newList.get(k).getSn_list().size(); l++) {
                    addSNCodeView(context , newList.get(k).getSn_list().get(l).getSn_code());
                    newSNList = newList.get(k).getSn_list();
                }
                continue;
            }
            addPackagingCodeView(context , newList.get(k).getPackage_code());
        }
    }
    private void backAndUpdate() {
        String checkResult = checked();
        if (checkResult == null) {
            updateInfo(CYInStorageNoInStorageMaterielDetailActivity.this);
            super.onBackPressed();
        } else {
            DialogUtils.getConfirmDialog(CYInStorageNoInStorageMaterielDetailActivity.this, checkResult + "\n" + getResources().getString(R.string.activity_change_storage_materiel_detail_whether_to_force_out), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    updateInfo(CYInStorageNoInStorageMaterielDetailActivity.this);
                    CYInStorageNoInStorageMaterielDetailActivity.super.onBackPressed();
                }
            }).show();
        }
    }

    private void ckeckSearch (Context context , String condition) {
        CYInStorageCheckSNCodeRequestBean bean = CYInStorageUtils.getCheckSNCodeBean (condition , stock_input_id);
        CYInStorageProductionCheckSearchRequest.request(context, bean, new GsonBeanListener<CYInStorageProductionCheckSearchBean>() {
            @Override
            public void onSuccess(CYInStorageProductionCheckSearchBean bean) {
                if (bean.getBody().getType().equals(PACKAGING_CODE)) {
                    if (checkPackagingCode(bean.getBody().getPackage_id() , condition)) {
//                        if (newSNList.size() == 0) {
//                            Utils.middleToast(context , "请先添加序列号");
//                        }else {
                            savePackagingCode(context , condition , bean.getBody().getPackage_id() , bean.getBody().getSn_list() );
//                        }
                    }
                }else if (bean.getBody().getType().equals(SERIAL_NUMBER)) {
                    if (checkSNCode(condition)) {
//                        addSNCodeView(context , condition );
                        saveSNCode(context ,condition , bean.getBody().getSn_list().get(0).getSn_id() );
                    }
                }
            }

            @Override
            public void onFailing(CYInStorageProductionCheckSearchBean bean) {
                super.onFailing(bean);
                Utils.middleToast(context , "请输入正确的内容");
            }
        });

    }
    @Override
    protected void onActivityResultImpl(int requestCode, int resultCode, Intent data) {
        super.onActivityResultImpl(requestCode, resultCode, data);
        if (requestCode == ChangeStorageExtra.SELECT_MATERIAL_CODE && resultCode == ChangeStorageExtra.SELECT_MATERIAL_CODE) {
            receiveMaterialCode = data.getStringExtra(ChangeStorageExtra.MATERIAL_CODE);
//            addChangeStorageMaterielListData(CYInStorageProductionCompleteMaterielDetailActivity.this , materielList , true);
        }
    }

    //校验打包码，已经添加过的打包码不能重复添加，跨物料
    private boolean checkPackagingCode (String id , String condition) {
//        if (packagingCodelist == null ) {
//            packagingCodelist = new ArrayList<>();
//        }
//        if (packagingCodelist.size() != 0) {
//            for (int i = 0; i < packagingCodelist.size(); i++) {
//                LogUtils.i("packagingCodelist =================" + packagingCodelist.get(i).getCode());
//                if (packagingCodelist.get(i).getCode().equals(condition)) {
//                    Utils.middleToast(CYInStorageNoInStorageMaterielDetailActivity.this , "已经存在该打包码，不能重复添加");
//                    //已经存在该打包码，不能重复添加
//                    return false;
//                }
//            }
//        }
//        CYInStorageStringBean bean = new CYInStorageStringBean();
//        bean.setId(id);
//        bean.setCode(condition);
//        packagingCodelist.add(bean);
        for (int i = 0; i < packagingCodelist.size(); i++) {
            LogUtils.i("packagingCodelist =================" + packagingCodelist.get(i).getCode());
            if (packagingCodelist.get(i).getCode().equals(condition)) {
                packagingCodelist.remove(i);
                return true;
            }
        }
        return false;
    }

    //校验序列号，输入的序列号如果不在服务器返回的序列号list中的话不能添加
    private boolean checkSNCode (String condition) {
        for (int i = 0; i < serialNumberlist.size(); i++) {
            LogUtils.i("serialNumberlist =================" + serialNumberlist.get(i).getSn_code());
            if (serialNumberlist.get(i).getSn_code().equals(condition)) {
                serialNumberlist.remove(i);
                return true;
            }
        }
        return false;
    }
    //添加打包码view
    private void addPackagingCodeView (Context context , String condition) {
        CYInStorageUtils.createPackagingCode(context, packagingCodeLayout, PACKAGING_CODE, condition, i, new CYInStorageProductionCompleteMaterielDetailActivity.InStorageMaterielListener() {
            @Override
            public void onNoDoubleClickListener(String condition) {
                List<SNItemInfo> snList = CYInStorageUtils.getPackageDetail(newList , condition);
                Intent intent = new Intent(context, CYInStorageSerialNumberActivity.class);
                intent.putExtra(OutStorageExtra.SN_LIST, (Serializable) snList);
                startActivity(intent);
            }

            @Override
            public void onDeleteClickListener(int id, String code) {
                LogUtils.i("id ===== " + id  + "    code ==== " + code);
                deletePackagingCodeView(id ,code);
            }
        });
        i += 1;

    }
    //添加序列号view
    private void addSNCodeView (Context context , String condition ) {

        CYInStorageUtils.createPackagingCode(context , serialNumberLayout ,SERIAL_NUMBER ,condition , i , new CYInStorageProductionCompleteMaterielDetailActivity.InStorageMaterielListener() {
            @Override
            public void onNoDoubleClickListener(String condition) {

            }

            @Override
            public void onDeleteClickListener(int id, String code) {
                LogUtils.i("id ===== " + id  + "    code ==== " + code);
                deleteSNCode(id , code);
            }

        });
        i += 1;//id增加1
    }

    //保存关联的打包码
    private void savePackagingCode (Context context , String code , String id , List<CYInStorageProductionCheckSearchBean.BodyBean.SnListBean> sn_list) {
//        for (int k = 0; k < newList.size(); k++) {
//            if (newList.get(k).getPackage_code().equals(code)) {
//                for (int l = 0; l < newSNList.size(); l++) {
//                    SNBean.SNInfoBean.SnListBean bean = newSNList.get(l);
//                    newList.get(k).getSn_list().add(bean);
//                    serialNumberLayout.removeAllViews();
//                }
//                return;
//            }
//        }

            //每添加一个序列号打包数量加1
            Float number = Float.parseFloat(packagingNumber.getText().toString()) + sn_list.size();
            //判断添加的数量是否大于生产数量，如果大于，返回
            if (number > Float.parseFloat(productionNumber.getText().toString())) {
                Utils.middleToast(context , "入库数量不能大于生产数量");
                return;
            }
            packagingNumber.setText(number.toString());

        addPackagingCodeView(context , code);
        SNBean.SNInfoBean snInfoBean = new SNBean.SNInfoBean();
        snInfoBean.setPackage_code(code);
        snInfoBean.setPackage_id(id);
        List<SNBean.SNInfoBean.SnListBean> list = new ArrayList<>();
        for (int k = 0; k < sn_list.size(); k++) {
            SNBean.SNInfoBean.SnListBean bean = new SNBean.SNInfoBean.SnListBean();
            bean.setSn_id(sn_list.get(k).getSn_id());
            bean.setSn_code(sn_list.get(k).getSn_code());
            list.add(bean);
        }
        snInfoBean.setSn_list(list);
        newList.add(snInfoBean);
        for (int k = 0; k < newSNList.size(); k++) {
            LogUtils.i("Sn_code ================================== " + newSNList.get(k).getSn_code());
        }
//        newSNList = new ArrayList<>();
//        serialNumberLayout.removeAllViews();
    }

    //保存扫描的序列号
    private void saveSNCode (Context context , String code , String id ) {

            //每添加一个序列号打包数量加1
            Float number = Float.parseFloat(packagingNumber.getText().toString()) + 1;
            //判断添加的数量是否大于生产数量，如果大于，返回
            if (number > Float.parseFloat(productionNumber.getText().toString())) {
                Utils.middleToast(context , "入库数量不能大于生产数量");
                return;
            }
            packagingNumber.setText(number.toString());
        addSNCodeView(context , code);
        SNBean.SNInfoBean.SnListBean bean = new SNBean.SNInfoBean.SnListBean();
        bean.setSn_code(code);
        bean.setSn_id(id);
        newSNList.add(bean);
    }

    //删除打包码
    private void deletePackagingCodeView (int id , String code) {
        List<SNBean.SNInfoBean.SnListBean> list = new ArrayList<>();
        //删除打包码项
        for (int k = 0; k < newList.size(); k++) {
            if (newList.get(k).getPackage_code().equals(code)) {
                list = newList.get(k).getSn_list();
                newList.remove(k);
                break;
            }
        }

//        把打包码放回需要校验的打包码list中
        CYInStorageStringBean bean = new CYInStorageStringBean();
        bean.setCode(code);
        bean.setId("");
        packagingCodelist.add(bean);
//        for (int k = 0; k < list.size(); k++) {
//            serialNumberlist.add(list.get(k));
//        }

        //把打包码项移除
        packagingCodeLayout.removeView(findViewById(id));
        //每删除一个打包码打包数量减序列号数量
        Float number = Float.parseFloat(packagingNumber.getText().toString()) - list.size();
        packagingNumber.setText(number.toString());
    }

    //删除序列号
    private void deleteSNCode (int id , String code) {
        SNBean.SNInfoBean.SnListBean bean = new SNBean.SNInfoBean.SnListBean();
        //从序列号list中移除
        for (int k = 0; k < newSNList.size(); k++) {
            if (newSNList.get(k).getSn_code().equals(code)) {
                bean = newSNList.get(k);
                newSNList.remove(k);
                break;
            }
        }
        //把删除的序列号放回需要校验的序列号list中
        serialNumberlist.add(bean);
        serialNumberLayout.removeView(findViewById(id));
        //每删除一个序列号打包数量减1
        Float number = Float.parseFloat(packagingNumber.getText().toString()) - 1;
        packagingNumber.setText(number.toString());
    }

    private String checked () {
        String result = null;
        if (Float.parseFloat(packagingNumber.getText().toString()) != Float.parseFloat(productionNumber.getText().toString())) {
            result = "入库数量不等于生产数量";
        }
        return result;
    }
    private void updateInfo (Context context) {
        //如果有未关联的序列号，则保存为打包码为空
        if (newSNList .size() != 0) {
            for (int k = 0; k < newList.size(); k++) {
                if (TextUtils.isEmpty(newList.get(k).getPackage_code())) {
                    newList.get(k).setSn_list(newSNList);
                    CYInStorageUtils.updateNoInStorageInformation(context , newList , packagingCodelist , serialNumberlist , matId , packagingNumber.getText().toString());
                    return;
                }
            }
            SNBean.SNInfoBean snInfoBean = new SNBean.SNInfoBean();
            snInfoBean.setPackage_code("");
            snInfoBean.setPackage_id("");
            snInfoBean.setSn_list(newSNList);
            newList.add(snInfoBean);
        }
        for (int k = 0; k < newList.size(); k++) {
            LogUtils.i("newlistPackage ==== "+ newList.get(k).getPackage_code());
            for (int l = 0; l < newList.get(k).getSn_list().size(); l++) {
                LogUtils.i("newlistSNCode ==== "+  newList.get(k).getSn_list().get(l).getSn_code());
            }
        }
        CYInStorageUtils.updateNoInStorageInformation(context , newList , packagingCodelist , serialNumberlist , matId , packagingNumber.getText().toString());
    }
    @Override
    public void onBackPressed() {
        backAndUpdate();
    }
}
